import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class UserService {
  constructor(private readonly prismaService: PrismaService) {}
  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  findAll() {
    return `This action returns all user`;
  }

  async findOne(id: number) {
    try {
      const res = await this.prismaService.user.findUnique({
        where: {
          id,
        },
        include: {
          Support: {
            select: {
              id: true,
              postId: true,
            },
          },
        },
      });
      delete res.password;
      return res;
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }

  async getPermissionByRolesId(rolesIds: number[]) {
    const res = this.prismaService.role.findMany({
      where: {
        id: {
          in: rolesIds,
        },
      },
      include: {
        RoleToPermission: {
          select: {
            permission: true,
          },
        },
      },
    });

    return res;
  }

  async getPostByUserId(id: number) {
    return this.prismaService.post.findMany({
      where: {
        userId: id,
      },
      include: {
        User: {
          select: {
            username: true,
            avatar: true,
          },
        },
      },
    });
  }
}
